import { Game, game, sys } from "cc";
import { tyqLayerManager } from "../Managers/TyqLayerManager";
import { tyqConstants } from "../Constans/TyqConstants";
import { GNetConf } from "../Constans/Conf1";
import { EType, IPos } from "../UI/WXCustomAd";
import { Channel, tyqAdManager } from "../Managers/TyqAdManager";
import { tyqSDKConfig } from "../Constans/TyqSDKConfig";

export interface jumpIconData {
    name: string,
    appid: string,
    imgUrl: string,
    weixin_ads_data: string,
    key: string,
}

export enum TyqSDKAppVersion {
    VERSION_1 = 1,
    VERSION_2 = 2
}

export enum ChannelFlag {
    // 微信小游戏-末日特工队
    WECHAT_FZDGR = 1,
   

}

class TyqSDK {
    public static readonly instance = new TyqSDK();

    /**开关对象合集 */
    private switch_info: any = {};
    /**总开关 1是开 0是关*/
    private master_switch: number = 0;
    /**用户唯一openID */
    private openid: string = ""
    /**游玩时间 */
    private _playTime: number = 0;


    private _gameLevel: number = 0;
    private item_openId = "tyq_item_openid";
    private item_watermark = "tyq_item_watermark_";
    private _watermark: string = "";
    private _onlineTime = 0;

    public weixin_ads_data: Array<Object>[][] = null;
    public wxGameIconData: Array<jumpIconData> = [];

    // 完成关卡数累计
    private levelCount: number = 0;
    // 服务器与本地的时间差，单位：秒
    private timeDiff: number = 0;

    // 打包渠道标识
    public channel;

    // 开始分享时间点
    private shareTime: Date;
    // 分享结果回调
    private shareCallback: Function;

    public initGame() {
        this.channel = ChannelFlag.WECHAT_FZDGR;
        this.setLogOpen(true);
        this.setAppVersion(1);
        if (tyqAdManager.getChannel() == Channel.ANDROID_233) {
            this.init("TyqApp20230213163724", "1iK3I97Mx6VuTjPKgUur1RUeV2eHH3OB"); //233apk
        } else if (tyqAdManager.getChannel() == Channel.ANDROID_4399) {
            this.init("TyqApp20230214154427", "o4gt48BCrJHyAxBco6aY6ydxwhPsJUxl"); //4399apk
        } else if (tyqAdManager.getChannel() == Channel.WECHAT) {
            switch (this.channel) {
                case ChannelFlag.WECHAT_FZDGR:
                    this.init("TyqApp20230424164228", "pkPn3WXxSNafexYgu4dstJYiBpgXKAPw"); // 微信小游戏
                    break;
           
            }
        }
    }

    /**
     * @returns 返回真实的url
     */
    public getUrl() {
       
    }


    /**
     * 初始化接口，尽量早调用
     * @param appId 运营后台提供 
     * @param apiKey 运营后台提供 
     * @param cb 初始化结果回调 st:1成功  st:0失败
     */
    public init(appId: string, apiKey: string, cb?: (st: number) => void) {
        tyqSDKConfig.appId = appId;
        tyqSDKConfig.apiKey = apiKey;


        this._watermark = sys.localStorage.getItem(this.item_watermark) || "";
        this.openid = this.initOpenId();
        if (tyqAdManager.getChannel() != Channel.WECHAT) {
            tyqAdManager.initAdIds();
        }

        this.ht1tpPost("api/v1/switch_info", null, (ret: any) => {
            if (ret.data) {
                this.timeDiff = ret.data.current_time_stamp - this.getTimeStamp(true);

                this.switch_info = ret.data.switch_info;
                this.master_switch = ret.data.master_switch;
                if (tyqAdManager.getChannel() == Channel.WECHAT) {
                    tyqAdManager.initAdIds();
                }


                if (ret.data.weixin_ads_data) {
                    this.weixin_ads_data = ret.data.weixin_ads_data;
                    for (let key in this.weixin_ads_data) {
                        let arr = [];
                        this.log('key', key);
                        if (typeof (key)) {
                            for (let i = 0; i < this.weixin_ads_data[key].length; i++) {
                                arr = [];
                                for (let keys in this.weixin_ads_data[key][i]) {
                                    arr.push(this.weixin_ads_data[key][i][keys]);
                                }
                                var jumpIconData: jumpIconData = {
                                    name: arr[0],
                                    appid: arr[1],
                                    imgUrl: arr[2],
                                    weixin_ads_data: arr[3],
                                    key: key,
                                }
                                this.wxGameIconData.push(jumpIconData);
                            }
                        }
                    }
                }
            }
            this.login();
            if (cb) {
                cb(1);
            }
        }, () => {
            if (cb) {
                cb(0);
            }
        });

        //开始统计玩家停留时间
        this._onlineTime = this.getTimeStamp();
        game.on(Game.EVENT_HIDE, () => {
            this.collectPlayeTime();
        });
        game.on(Game.EVENT_SHOW, () => {
            this._onlineTime = this.getTimeStamp();
            if (this.shareTime) {
                let dt = new Date().getTime() - this.shareTime.getTime();
                this.shareTime = undefined;
                if (dt >= 3000) {
                    if (this.shareCallback) {
                        this.shareCallback();
                        this.shareCallback = undefined;
                    }
                }
            }
        })
    }

    /**
     * 登陆接口，初始化接口回调成功后调用
     */
    private login() {
        if (!this.openid) {
            this.error("openId为空");
            return;
        }

        let urlQuery = tyqAdManager.getEnterUrlQuery();

        let obj: any = {};
        if (urlQuery) {
            if (urlQuery.ads_id) {
                obj.ads_id = urlQuery.ads_id;
            }
            if (urlQuery.source_openid) {
                obj.source_openid = urlQuery.source_openid;
            }
            if (urlQuery.pull_in_ads_id) {
                obj.pull_in_ads_id = urlQuery.pull_in_ads_id;
            }
        }
        this.ht1tpPost("api/v1/login", obj, (res: any) => {
            this.log("登陆：" + this.openid);
            if (res.data) {
                this._watermark = encodeURIComponent(res.data.watermark);
                sys.localStorage.setItem(this.item_watermark, this._watermark);
            }
        }, () => {
            this.error("登录失败,网络错误");
        });
    }

    /**
     * 分享  id=1&name=111
     * @param params 分享url参数 格式：key1=val1&key2=val2
     * @param cb 有回调，就代表分享成功
     */
    share(params?: string, cb?: Function) {
        if (tyqAdManager.getChannel() == Channel.WECHAT) {
            this.shareTime = new Date();
            this.shareCallback = cb;
            wx.shareAppMessage({
                query: params
            });
        }
    }

    /**
     * 用于区分审核版和正式版的开关参数 1和2，对应后台版本一和版本二参数设置 默认值：1
     * 注意：该接口要在init接口调用之前调用才有效
     * @param version 
     */
    public setAppVersion(version: TyqSDKAppVersion) {
        tyqSDKConfig.appVersion = version;
    }

    /**
     * 直接获取开关值，优先判断总开关，总开关如果是关的，那将全部返回关闭状态
     */
    public getSwitchValue(str: string, df?: any): any {
        if (this.master_switch == 0) {
            return 0;
        }
        if (!this.switch_info[str]) {//不存在这个开关
            this.log(str + "开关不存在");
            return df || 0;
        } else if (this.switch_info[str] == "0") {
            return 0;
        } else {
            return this.switch_info[str];
        }
    }
    /**
     * 概率开关值
     * @param str 
     * @returns 
     */
    public getConfigProbability(str: string) {
        let value = this.getSwitchValue(str);
        if (!value) {
            return false;
        }
        let rand = Math.random();
        if (rand < value) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 收集用户玩游戏停留时间
     */
    private collectPlayeTime() {
        if (!this.openid) {
            this.error("没有openid");
            return;
        }

        var nowTime = this.getTimeStamp();
        let elapsed = nowTime - this._onlineTime;
        this.log("上传停留", elapsed);
        let info = {
            duration_time: elapsed
        }
    }

    private ht1tpPost(url: string, info: any, successCb?: Function, failCb?: Function) {
      
    }

    public wxIconData(): Array<jumpIconData> {
        return this.wxGameIconData;
    }
    public wxJumpData(): Array<Object> {
        return this.weixin_ads_data;
    }

    /**
     * 收集用户点击跳转信息，关于跳转后台小游戏接口触活量统计
     * @param event 时间名称
     * @param weixin_ads_id 后台所对应图片展示位
     */
    public collectClickEventGame(event: string, weixin_ads_id: string) {
        if (!this.openid) {
            this.error("没有openid");
            return;
        }
        let info = {
            event_id: event,
            weixin_ads_id: weixin_ads_id,
        }
        this.ht1tpPost("api/v1/collect_weixin_ads_jumb_ok_cb", info);
    }

    /**
     * 获取随机字符串
    */
    private randomStr(strLen: number = 32) {
        let len = strLen;
        let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        let maxPos = $chars.length;
        let pwd = '';
        for (let idx = 0; idx < len; idx++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }

    /**
     * 获取时间戳
     * @param isSecond true 单位：秒    默认单位：毫秒
     * @returns 
     */
    private getTimeStamp(isSecond = false) {
        let time = Date.now();
        if (isSecond) {
            time = Math.floor(time / 1000);
        }
        return time;
    }

    /**
     * openId初始化
     */
    private initOpenId(): string {
        let openId = sys.localStorage.getItem(this.item_openId);
        if (!openId) {
            openId = this.randOpenId();
            sys.localStorage.setItem(this.item_openId, openId);
            this.log("注册：" + openId);
        }
        this.log("openid=", openId);

        return openId;
    }
    private randOpenId() {
        var s = [], hexDigits = "0123456789abcdef";
        for (var i = 0; i < 40; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
        s[8] = s[13] = s[18] = s[23] = s[28] = "-";
        return s.join("");
    }

    /**
     * 埋点事件：某个关卡开始时调用
     * @param level 第几个关卡
     */
    public eventLevelStart(level: number) {
        this._gameLevel = level;
        this.collectLevelInfo(1);
    }
    /**
     * 埋点事件：关卡挑战结束时调用
     * @param level 第几个关卡
     * @param isWin 是否成功
     */
    public eventLevelEnd(level: number, isWin: boolean) {
        this._gameLevel = level;
        this.collectLevelInfo(isWin ? 2 : 3);
    }
    /**
     * 自定义埋点事件
     * @param eventType 事件类型 
     * @param eventName 事件名称
     */
    public eventSendCustomEvent(eventType: string, eventName?: string) {
        if (!this.openid) {
            this.error("没有openid");
            return;
        }
        let name = eventName ? eventType + "-" + eventName : eventType;
        this.log("%cevent:" + name, "color:#FF0000");
        let info = {
            event_id: name,
        }
        this.ht1tpPost("api/v1/collect_click_event", info);
    }

    public adClickUpload(adType: string, mode: string, action: number, pagePath: string) {
        if (!this.openid) {
            this.error("没有openid");
            return;
        }
        if (pagePath) {
            pagePath = encodeURIComponent(pagePath);
        }
        this.log("广告点击上报：" + adType, mode, action, pagePath);

        let status = 0;
        if (adType == tyqSDKConfig.adShowTypes.rewardedAd) {
            status == 1;
        } else if (adType == tyqSDKConfig.adShowTypes.interstitialAd) {
            status = 2;
        } else if (adType == tyqSDKConfig.adShowTypes.bannerAndCustomAd) {
            status = 3;
        }

        let info: any = {};
        info.status = status;
        let urlQuery = tyqAdManager.getEnterUrlQuery();
        if (urlQuery && urlQuery.pull_in_ads_id) {
            info.pull_in_ads_id = urlQuery.pull_in_ads_id;
        }
        this.ht1tpPost("api/v1/collect_weixin_ads_mb_act_info", info);
    }


    /**
     * 收集关卡游玩信息
     * @param stata 1：关卡挑战开始  2：胜利  3：失败
     */
    private collectLevelInfo(stata: number) {
        if (!this.openid) {
            this.error("没有openid");
            return;
        }
        let curTime = this.getTimeStamp(false);
        var play_time = 0;
        if (stata == 1) {
            // 关卡开始，记录下开始时间点
            this._playTime = curTime;
        } else {
            // 关卡结束，计算花费时长
            play_time = curTime - this._playTime;
            this._playTime = 0;
        }

        let info = {
            game_level: this._gameLevel,
            status: stata,
            play_time: play_time
        }
        this.ht1tpPost("api/v1/collect_user_play_game_level", info);
    }

    /**
     * 设置SDK输出日志开关，默认是关闭的
     * @param isOpen 
     */
    public setLogOpen(isOpen: boolean) {
        tyqSDKConfig.isLogOpen = isOpen;
    }

    public log(message?: any, ...optionalParams: any[]) {
        if (!tyqSDKConfig.isLogOpen) {
            return;
        }
        if (typeof (message) == "string") {
            console.log("[TyqSDK]" + message, ...optionalParams);
        } else {
            console.log("[TyqSDK]", message, ...optionalParams);
        }
    }
    public error(message?: any, ...optionalParams: any[]) {
        if (!tyqSDKConfig.isLogOpen) {
            return;
        }
        console.error("[TyqSDK]" + message, ...optionalParams);
    }


    // 广告相关接口===========================================start
    /**
     * 显示底部banner广告，内部有调用计数机制，调用+1，调用hideBannerAd会减1，计数为0才会真正隐藏banner广告
     * @param forceShow true:表示强制显示，不管后台开关配置如何 
     */
    public showBannerAd(forceShow?: boolean) {
        let time = this.getSwitchValue(tyqSDKConfig.paramsKeys.tyq_banner_turns);
        if (time) {
            tyqAdManager.showBannerAd(parseInt(time));
            return;
        }
        if (forceShow) {
            tyqAdManager.showBannerAd();
            return;
        }
    }
    /**
     * 隐藏bannner广告
     * @param isForce 是否强制将计数置为零，并强制隐藏
     */
    public hideBannerAd(isForce?: boolean) {
        tyqAdManager.hideBannerAd(isForce);
    }
    /**
     * banner广告是否正在显示中
     */
    public isBannerAdShowing(): boolean {
        return tyqAdManager.isBannerAdShowing();
    }

    /**
     * 显示插屏广告
     */
    public showInterstitialAd() {
        tyqAdManager.showInterstitialAd();
    }

    /**
     * 显示原生矩阵广告
     */
    public showCustomRectCenterAd(failcb = null) {
        tyqAdManager.showCustomRectCenterAd(failcb);
    }
    /**
     * 隐藏原生矩阵广告
     */
    public hideCustomRectCenterAd() {
        tyqAdManager.hideCustomRectCenterAd();
    }

    /**
     * 显示原生垂直广告，显示在左右两边
     * @param forceShow true:表示强制显示，不管后台开关配置如何 
     */
    public showCustomVerticalLeftRightAd(forceShow?: boolean) {
        if (forceShow || this.getSwitchValue(tyqSDKConfig.paramsKeys.tyq_custom_v_switch)) {
            tyqAdManager.showCustomVerticalLeftRightAd();
        }
    }
    /**
     * 隐藏原生垂直广告
     */
    public hideCustomVerticalLeftRightAd() {
        tyqAdManager.hideCustomVerticalLeftRightAd();
    }

    /**
     * 显示原生水平广告，显示在顶部
     * @param forceShow true:表示强制显示，不管后台开关配置如何 
     */
    public showCustomHorizontalTopAd(forceShow?: boolean) {
        if (forceShow || this.getSwitchValue(tyqSDKConfig.paramsKeys.tyq_custom_h_switch)) {
            tyqAdManager.showCustomHorizontalTopAd();
        }
    }
    /**
     * 隐藏原生水平广告
     */
    public hideCustomHorizontalTopAd() {
        tyqAdManager.hideCustomHorizontalTopAd();
    }

    /**
     * 通用显示原生广告接口
     * @param flag 标识 
     * @param type 类型 1矩阵；2横向；3竖向；4单格子
     * @param pos 位置信息
     * @param adSize 尺寸
     * @param adId 广告id
     * @param failcb 失败回调
     */
    public showCustomAd(flag: string, type: EType, pos: IPos, adSize?: { width: number, height: number }, adId?: any, failcb?: Function) {
        if (!adSize) {
            switch (type) {
                case EType.rect:
                    adSize = tyqAdManager.customAdSizeObj.rect;
                    break;
                case EType.horizontal:
                    adSize = tyqAdManager.customAdSizeObj.horizontal;
                    break;
                case EType.vertical:
                    adSize = tyqAdManager.customAdSizeObj.vertical;
                    break;
                default:
                    adSize = tyqAdManager.customAdSizeObj.gird;
                    break;
            }
        }
        tyqAdManager.showCustomAd(flag, type, pos, adSize, adId, failcb);
    }
    /**
     * 根据创建标识隐藏原生广告
     * @param flag 
     */
    public hideCustomAd(flag: string) {
        tyqAdManager.hideCustomAd(flag);
    }

    /**
     * 隐藏所有原生广告
     */
    public hideCustomAllAd() {
        tyqAdManager.hideCustomAllAd();
    }

    /**
     * 修改通用原生矩阵广告的尺寸
     * 后台默认参数 行数：5
     * @param width 
     * @param height 
     */
    public setCustomRectAdSize(width: number, height: number) {
        tyqAdManager.customAdSizeObj.rect.width = width;
        tyqAdManager.customAdSizeObj.rect.height = height;
    }
    /**
     * 修改通用原生水平广告的尺寸
     * 后台默认参数 尺寸：80%  默认数：5
     * @param width 
     * @param height 
     */
    public setCustomHorizontalAdSize(width: number, height: number) {
        tyqAdManager.customAdSizeObj.horizontal.width = width;
        tyqAdManager.customAdSizeObj.horizontal.height = height;
    }
    /**
     * 修改通用原生垂直广告的尺寸
     * 后台默认参数 尺寸：90%  默认数：5
     * @param width 
     * @param height 
     */
    public setCustomVerticalAdSize(width: number, height: number) {
        tyqAdManager.customAdSizeObj.vertical.width = width;
        tyqAdManager.customAdSizeObj.vertical.height = height;
    }
    /**
     * 修改通用原生单个格子广告的尺寸
     * 后台默认参数 单个格子 尺寸：90%
     * @param width 
     * @param height 
     */
    public setCustomGridAdSize(width: number, height: number) {
        tyqAdManager.customAdSizeObj.grid.width = width;
        tyqAdManager.customAdSizeObj.grid.height = height;
    }

    /**
     * 显示激励视频广告
     * @param info 观看激励视频位置描述，如果有值，会自动埋点该位置的观看激励视频与观看完激励视频事件
     * @param cb 结果回调，参数st  1成功，发放奖励   其他失败
     */
    public showRewardedAd(info?: string, cb?: (st: number) => void) {
        if (info) {
            this.eventSendCustomEvent(tyqSDKConfig.eventNames.rewardedAdStart + info);
        }
        tyqAdManager.showRewardedAd(() => {
            if (info) {
                this.eventSendCustomEvent(tyqSDKConfig.eventNames.rewardedAdSuccess + info);
            }
            if (cb) {
                cb(1);
            }
        }, (st: number) => {
            if (cb) {
                cb(st);
            }
        });
    }

    // 广告相关接口===========================================end
    /**
     * 进入加载页，需要调用该接口
     */
    public onShowLoadingLayer() {
        this.eventSendCustomEvent(tyqSDKConfig.eventNames.enterLoadingLayer);
    }

    /**
     * 游戏显示主界面，需要调用该接口
     */
    public onShowHomeLayer() {
        this.eventSendCustomEvent(tyqSDKConfig.eventNames.enterHomeLayer);

        let val = this.getSwitchValue(tyqSDKConfig.paramsKeys.tyq_show_main_layer);
        if (!val) {
            return;
        }
        val = parseInt(val);
        if (val == 1) {
            // 显示插屏广告
            this.showInterstitialAd();
        } else if (val == 2) {
            // 显示矩阵广告
            this.showCustomRectCenterAd(null);
        }
    }

    /**
     * 完成某局或者某个关卡，需要调用该接口，不管成功或者失败，都要调用
     * @param level 当前进行到的关卡
     */
    public addLevelCount(level: number) {
        let startLevel = this.getSwitchValue(tyqSDKConfig.paramsKeys.tyq_reward_level);
        if (!startLevel) {
            return;
        }

        startLevel = parseInt(startLevel);
        if (level <= startLevel) {
            return;
        }

        this.levelCount++;
        let val = tyqSDK.getSwitchValue(tyqSDKConfig.paramsKeys.tyq_level_count);
        if (val) {
            val = parseInt(val);
            if (this.levelCount >= val) {
                this.levelCount = 0;
                this.showRewardedAd();
            }
        }
    }

    /**
     * 游戏显示结算界面，需要调用该接口
     */
    public onShowSettlementLayer() {
        this.showInterstitialAd();
    }

    /**
     * 在游戏结算界面展示之前，调用该接口，显示SDK的【更多游戏】界面
     * @param level 当前进行到的关卡
     * @param closeCb 更多游戏界面关闭后的回调，继续执行展示游戏结算界面的逻辑
     */
    public showMoreGameLayer(level: number, closeCb: Function) {
        if (tyqAdManager.getChannel() != Channel.WECHAT) {
            return
        }
        let startLevel = this.getSwitchValue(tyqSDKConfig.paramsKeys.tyq_more_game_level);
        if (!startLevel) {
            closeCb();
            return;
        }

        startLevel = parseInt(startLevel);
        if (level <= startLevel) {
            closeCb();
            return;
        }

        let obj: any = {};
        obj.level = level;
        tyqLayerManager.openLayer(tyqConstants.layers.TyqMoreGameLayer, obj, () => {
            closeCb();
        });

    }

}

export const tyqSDK = TyqSDK.instance;
